package com.tao.power.Service.ServiceImpl;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.StrUtil;
import com.tao.power.Dao.LoginMapper;
import com.tao.power.Dto.Result;
import com.tao.power.Dto.RolerPowerDto;
import com.tao.power.Pojo.User;
import com.tao.power.Service.LoginService;
import com.tao.power.Enums.ErrorEnums;
import com.tao.power.Utils.tokenUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
public class LoginServiceImpl implements LoginService {

    @Resource
    private LoginMapper loginMapper;

    @Override
    public Result Login(String username, String password, HttpServletRequest request) {
        User user = loginMapper.Login(username, password);
        if (user == null) {
            return Result.fail(ErrorEnums.Login_Fail.getLabel(), ErrorEnums.Login_Fail.getValue());
        }
        if(user.getStatus().equals("0")){
            return Result.fail(ErrorEnums.NoStatus.getLabel(),ErrorEnums.NoStatus.getValue());
        }
        HttpSession session = request.getSession();
        String token = tokenUtils.createToken(username, password);
        session.setAttribute("token", token);
        session.setAttribute("user", user);
//        List<String> power = queryPowerByUser(user.getId());
//        session.setAttribute("power", power);
        Map<String, Object> map = new HashMap<>();
//        map.put("power", power);
        map.put("user", user);
        map.put("token", token);
        return Result.ok(ErrorEnums.Success.getLabel(), map, ErrorEnums.Success.getValue());
    }

    @Override
    public List<String> queryPowerByUser(Integer userId) {
        List<Integer> userIds = loginMapper.queryUserRoleId(userId);
        if (userIds.isEmpty()) {
            return new ArrayList<>();
        }
        List<Integer> collect = new ArrayList<>();
        List<String> powerIds = loginMapper.queryRolesByUser(userIds);
        if (powerIds.isEmpty()){
            return new ArrayList<>();
        }
        for (String powerId : powerIds) {
            String str = StrUtil.removePrefix(powerId, "[");
            String menuAddressStr = StrUtil.removeSuffix(str, "]");
            List<Integer> list = Arrays.stream(menuAddressStr.split(",")).map(b -> Integer.parseInt(b.trim())).collect(Collectors.toList());
            collect.addAll(list);
        }
        List<Integer> menuAddress = collect.stream().distinct().collect(Collectors.toList());
        return loginMapper.queryMenuAddstress(menuAddress);
    }
}
